//
//  YJCaiZhuHomeVC.m
//  YJB
//
//  Created by 高卫明 on 16/5/27.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "THHomeVC.h"
#import "THHomeBtnCell.h"
#import "HYBLoopScrollView.h"
#import "YJUserDefaultTool.h"
#import "YJNetworkTool.h"
#import "YJCPCWebView.h"
#import "THCPCHomeVC.h"
#import "THTaskHomeVC.h"
#import "THClassTableViewCell.h"
#import "THHotTableViewCell.h"
#import "THEarnAutoManualVC.h"


#import "THCPCEarnedTabBarVC.h"
#import "THTaskEarnTabBarVC.h"

#import "CPCEarnTabbarViewController.h"
#import "MissionTabBarViewController.h"

#import "TrafficEnterViewController.h"


@interface THHomeVC ()
@property(nonatomic,weak)HYBLoopScrollView *adScrollView;
@property(nonatomic,weak)UIButton *button;
@property(nonatomic,strong) NSMutableDictionary *param;
@property(nonatomic,strong) NSString *theAction;
@property(nonatomic,strong) NSString *theURL;
@property(nonatomic,strong) NSString *theNavTitle;
/**点击签到赚钱 弹出广告view*/
@property(nonatomic,weak)UIView        *view0;
@property(nonatomic,weak)UIImageView      *choiceView0;
@property(nonatomic,weak)UIButton       *choiceBtn0;
@property(nonatomic,weak)UIButton       *offBtn0;
@property(nonatomic,strong)NSString     *advURL;
@property(nonatomic,strong)NSString     *advImgUrl;
@property(nonatomic,strong)UILabel      *singGold;

/** 关闭广告按钮后 */
@property(nonatomic,strong)UIView        *background;
@property(nonatomic,weak)UIImageView      *choiceView;
@property(nonatomic,weak)UIButton       *choiceBtn;
@property(nonatomic,weak)UIButton       *offBtn;

@end

@implementation THHomeVC
{
    NSString *_signgoldNum;
}
-(void)dealloc
{
    [NOTIFICATIONCENTER removeObserver:self];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _signgoldNum = [[NSString alloc] init];
    [NOTIFICATIONCENTER addObserver:self selector:@selector(signEarnMoney) name:THSignEarnMoneyNotification object:nil];
    
    [self setupTableView];
    //头部广告
    self.tableView.tableHeaderView = self.adScrollView;
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    _param = [NSMutableDictionary dictionary];
    [self testTHHeprotocol];
    
}

- (void)testTHHeprotocol
{
    _param[@"action"] = @"set_verify_user";
    _param[@"makegold"] = @{@"username":[YJUserDefaultTool readUserName],
                            @"user_info":[YJUserDefaultTool readUserName],
                            @"phone_info":@"iOS",
                            @"md5_key":[[[[YJUserDefaultTool readUserName] stringByAppendingString:@"iOS"]stringByAppendingString:appMd5Key]md5],
                            @"password":[[YJKeychainTool readPassword] md5]
                            };
    MyLog(@"send %@",_param);
    [YJNetworkTool postWithUrl:@"http://www.a8vsc.com/makegold/yjb/tuhao/user.php" parameters:_param success:^(id responseObject) {
        MyLog(@"tuhao_verify_user :%@ %@",responseObject,responseObject[@"return"][@"message"]);
       
    } failure:^(NSError *error) {
        MyLog(@"faild %@",error);
    }];
}


- (void)postTO:(NSString *)postURL withTheAction:(NSString *)action navTitle:(NSString *)navtitle
{
    _param[@"action"] = action;
    _param[@"makegold"] = @{@"username":[YJUserDefaultTool readUserName]};
    MyLog(@"send %@ %@",_param,postURL);
    [YJNetworkTool postWithUrl:postURL parameters:_param success:^(id responseObject) {
        MyLog(@"flowEarnMoney :%@",responseObject);
        YJCPCWebView *cpcWebView = [[YJCPCWebView alloc]init];
        cpcWebView.urlStr = responseObject[@"return"];
        cpcWebView.navTitle = self.theNavTitle;
        [self.navigationController pushViewController:cpcWebView animated:YES];
    } failure:^(NSError *error) {
        MyLog(@"faild flowEarnMoney%@",error);
    }];
    
}

- (void)loadNewData
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,  (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
    });
}

- (void)setupTableView
{
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.tableView registerClass:[THHomeBtnCell class] forCellReuseIdentifier:caiFuBtnCellID];
    [self.tableView registerClass:[THClassTableViewCell class] forCellReuseIdentifier:classBtnCellID];
    [self.tableView registerClass:[THHotTableViewCell class] forCellReuseIdentifier:hotCellID];
    self.tableView.tableFooterView = [UITableView new];
}

/**接收点击赚钱按钮的动作-----------------------------------*/
- (void)pushToTheEarnMoneyVC: (THHomeBtnCellButtonType)type
{
    switch (type)
    {
        case THHomeBtnCellFlowEarnMoney:
        {
            TrafficEnterViewController *earnMoneyVC = [[TrafficEnterViewController alloc] init];
            //THEarnAutoManualVC *earnMoneyVC = [THEarnAutoManualVC new];
            [self.navigationController pushViewController:earnMoneyVC animated:YES];
        }
        break;
        case THHomeBtnCellTaskEarnMoney:
        {
//         THTaskHomeVC *taskHomeVC = [[THTaskHomeVC alloc]init];
//          [self.navigationController pushViewController:taskHomeVC animated:YES];
        
//            [self.navigationController pushViewController:[MissionTabBarViewController new] animated:YES];
            [self.navigationController pushViewController:[THTaskEarnTabBarVC new] animated:YES];
        }
            
        break;
            
        case THHomeButtonCellCPCEarnMoney:
            
            [self.navigationController pushViewController:[THCPCEarnedTabBarVC new] animated:YES];
            
//            [self.navigationController pushViewController:[CPCEarnTabbarViewController new] animated:YES];
            
             //[self.navigationController pushViewController:[THCPCHomeVC new] animated:YES];
        break;
         case THHomeButtonCellGameEarnMoney:
            
        break;
        
       case THHomeOtherBtnEarnMoney:
            break;
    }
}

#pragma mark//签到赚钱按钮 判断是否已经签到  再出现广告view
- (void)signEarnMoney
{
    if (self.background.hidden == NO) {
        return;
    }
    _param[@"action"] = @"user_sign_in";
    _param[@"makegold"] = @{@"username":[YJUserDefaultTool readUserName],
                            @"user_info":[YJUserDefaultTool readUserName],
                            @"phone_info":@"iOS",
                            @"md5_key":[[[[YJUserDefaultTool readUserName] stringByAppendingString:@"iOS"]stringByAppendingString:appMd5Key]md5],
                            @"password":[[YJKeychainTool readPassword] md5]
                            };
    MyLog(@"send %@",_param);
    [MBProgressHUD showMessage:@"" toView:self.view];
    [YJNetworkTool postWithUrl:THURL(@"user_sign.php") parameters:_param success:^(id responseObject)
    {
        [MBProgressHUD hideHUDForView:self.view];
        MyLog(@"user_sign_in:%@ %@",responseObject,responseObject[@"return"][@"message"]);
        NSDictionary *dic = responseObject[@"return"];
        NSString *code = dic[@"code"];
        
        if (code.intValue == 200) //成功签到 弹出广告页
        {
            _signgoldNum = dic[@"data"][@"list"][@"sign_gold"];
            _advURL = dic[@"data"][@"list"][@"adv_url"];
            MyLog(@"adURL %@",_advURL);
            [self signAdvertiseView];
        }
        if (code.intValue == 301)
        {
            [MBProgressHUD showError:@"今日已签过到啦"];
        }
    } failure:^(NSError *error)
    {
        [MBProgressHUD hideHUDForView:self.view];
    }];
}

- (void)signAdvertiseView
{
    if (self.background.hidden == NO) {
        return;
    }
    
    self.background.hidden = NO;
    UIButton *btn = [[UIButton alloc] init];
    _offBtn = btn;
    [btn setImage:Image(@"关掉广告按钮") forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(firstOffBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.background addSubview:btn];

    UIImageView *view2 = [[UIImageView alloc] init];
    _choiceView = view2;
    [self.background addSubview:view2];
    _choiceView.image = Image(@"广告弹窗");
    [view2 mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.mas_equalTo(self.view.width*0.16);
         make.right.mas_equalTo(-self.view.width*0.16);
         make.width.mas_equalTo(view2.mas_height).multipliedBy(0.798);
         make.centerY.mas_equalTo(self.background.mas_centerY);
     }];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.right.equalTo(view2.mas_right).offset(3);
         make.width.mas_equalTo(40);
         make.height.mas_equalTo(45);
         make.top.equalTo(view2.mas_top).offset(-42);
     }];
}

#pragma mark//点击关闭广告view 
- (void)signOffBtn
{
    self.background.hidden = NO;
    [self.background mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.edges.equalTo(self.view).width.insets(UIEdgeInsetsMake(0, 0, 0, 0));
     }];
    
    UIButton *btn = [[UIButton alloc] init];
    _offBtn = btn;
    [btn setImage:Image(@"th_home_close") forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(offBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    UIButton *choicebtn = [[UIButton alloc] init];
    _choiceBtn = choicebtn;
    [self.background addSubview:choicebtn];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    _singGold = label;
#pragma mark -测试用
    //_singGold.backgroundColor = [UIColor purpleColor];
    UIImageView *view2 = [[UIImageView alloc] init];
    _choiceView = view2;
    [self.choiceBtn addSubview:view2];
    [self.background addSubview:btn];
    _choiceView.image = Image(@"签到提示界面");
    [_choiceView addSubview:_singGold];
    [_singGold mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(_choiceView).offset(-12);
        make.height.mas_equalTo(_choiceView.mas_height).multipliedBy(0.253);
        make.centerY.mas_equalTo(_choiceView.mas_centerY).offset((IPHONE_W-198)*0.127);
    }];
    
    NSMutableAttributedString *attr = [NSString attributedString:[NSString stringWithFormat:@"%@",_signgoldNum] fontColor:kUIColorFromRGB(0xfa5f3c) frontFont:FONT(18) behind:@" 金币" behindColor:kUIColorFromRGB(0xfa5f3c) behindFont:FONT(11)];
    _singGold.attributedText = attr;
    _singGold.textAlignment = NSTextAlignmentCenter;
    
    [view2 mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.right.top.bottom.mas_equalTo(self.choiceBtn);
     }];
    
    [choicebtn mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.mas_equalTo(89);
         make.right.mas_equalTo(-89);
         make.height.mas_equalTo(choicebtn.mas_width).multipliedBy(0.944);
         make.centerY.equalTo(self.background.mas_centerY);
     }];
    [btn mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.right.equalTo(view2.mas_right);
         make.width.mas_equalTo(40);
         make.height.mas_equalTo(40);
         make.top.mas_equalTo(view2.mas_top);
     }];

}

#pragma mark CPC赚钱协议测试
- (void)CPCEarnMoneyProtodolTest
{
    _param[@"action"] = @"add_ad_link";
    _param[@"makegold"] = @{@"user_name":[YJUserDefaultTool readUserName],
                            @"ad_name":@"day day up",
                            @"ad_link":@"http://cn.bing.com",
                            @"stop_sec":@"5",
                            @"fee":@"0.05",
                            @"day_fee":@"10000"
                            };
    MyLog(@"send:%@",_param);
    [YJNetworkTool postWithUrl:@"http://www.a8vsc.com/makegold/pdoconn/api_add_ad_link.php" parameters:_param success:^(id responseObject) {
        MyLog(@"add_ad res:%@",responseObject);
        [self CPCGetTheAddList];
    } failure:^(NSError *error) {
        MyLog(@"faild : %@",error);
    }];
    
}

- (void)CPCGetTheAddList
{
    _param[@"action"] = @"get_other_ad_list";
    _param[@"makegold"] = @{@"user_name":[YJUserDefaultTool readUserName],
                            @"curr_page":@"1",
                            @"size":@"15"
                            };
    MyLog(@"send:%@",_param);
    [YJNetworkTool postWithUrl:@"http://www.a8vsc.com/makegold/pdoconn/api_get_other_ad_list.php" parameters:_param success:^(id responseObject) {
        MyLog(@"add list res:%@",responseObject);
     //   cpcWebView.urlStr = responseObject[@"return"][@"ad_list"][@"url"];
      //  [self.navigationController pushViewController:cpcWebView animated:YES];
    } failure:^(NSError *error) {
        MyLog(@"faild get addList: %@",error);
    }];
    
}

- (void)firstOffBtnClick:(UIButton *)btn
{
    self.background.hidden = YES;
    [self.choiceView removeFromSuperview];
    [self.choiceBtn removeFromSuperview];
    [self.offBtn removeFromSuperview];
    
    _choiceBtn = nil;
    _offBtn = nil;
    _choiceView = nil;
    [self signOffBtn];
}

- (void)offBtnClick:(UIButton *)btn
{
    self.background.hidden = YES;
    [self.choiceView removeFromSuperview];
    [self.choiceBtn removeFromSuperview];
    [self.offBtn removeFromSuperview];
    _choiceBtn = nil;
    _offBtn = nil;
    _choiceView = nil;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.background.hidden = YES;
    [self.choiceView removeFromSuperview];
    _choiceView = nil;
}

- (void)click:(THHomeClassCellType)type
{
    switch (type) {
        case THHomeClassCellPrice:
        {
            MyLog(@"THHomeClassCellPrice");
        }
            break;
        case THHomeClassCellCPC:
        {
            MyLog(@"THHomeClassCellCPC");
        }
            break;
        case THHomeClassCellStore:
        {
            MyLog(@"THHomeClassCellStore");
        }
            break;
        case THHomeClassCellAdvert:
        {
            MyLog(@"THHomeClassCellAdvert");
        }
            break;
            
        default:
            break;
    }
}


#pragma mark ----------------------- 懒加载
-(HYBLoopScrollView  *)adScrollView
{
    if (_adScrollView == nil)
    {
        NSArray *adImageUrls = @[@"http://images.sun0769.com/sns_attachments/month_1206/12060718561bb1c00cfcf72875.jpg",@"http://img2.3lian.com/2014/c8/11/d/48.jpg",@"http://www.taopic.com/uploads/allimg/110915/15-1109150P62810.jpg"];
        HYBLoopScrollView *adScrollView = [HYBLoopScrollView loopScrollViewWithFrame:CGRectMake(0, 0, IPHONE_W, 14 * GRIDH) imageUrls:adImageUrls timeInterval:3 didSelect:^(NSInteger atIndex) {
            
        } didScroll:^(NSInteger toIndex) {
            
        }];
        
        adScrollView.placeholder = Image(@"banner");
        _adScrollView = adScrollView;
    }
    return _adScrollView;
}

#pragma mark --------------------- 表格代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 8;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    return section == 0?1:2;
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        THHomeBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:caiFuBtnCellID forIndexPath:indexPath];
        YJWeakSelf
        cell.thButtonClickBlock = ^(THHomeBtnCellButtonType type){
            [weakSelf pushToTheEarnMoneyVC:type];
        };
        return cell;
    }else if (indexPath.section == 1)
    {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        //cell.imageView.contentMode = UIViewContentModeScaleToFill;
        
        UIImageView *imageview = [[UIImageView alloc] init];
        UILabel *label = [[UILabel alloc] init];
        imageview.image = Image(@"tuhao_home_price");
        label.text = @"发布了“赢金宝注册”任务";
        label.font = FONT(15);
        [cell addSubview:imageview];
        [cell addSubview:label];
        
        [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(7);
            make.left.mas_equalTo(12);
            make.bottom.mas_equalTo(-7);
            make.width.equalTo(imageview.mas_height);
        }];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(imageview.mas_right).offset(15);
            make.right.mas_equalTo(-12);
            make.height.mas_equalTo(16);
            make.centerY.equalTo(imageview.mas_centerY);
        }];
        
        return cell;
    }else if (indexPath.section == 2)
    {
        THClassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:classBtnCellID forIndexPath:indexPath];
        YJWeakSelf;
        cell.thButtonClickBlock = ^(THHomeClassCellType type){
            [weakSelf click:type];
        };
        return cell;
    }else if (indexPath.section == 3)
    {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        cell.textLabel.font = FONT(15);
        
        NSString *text = @"土豪热门帖子";
        cell.textLabel.text = text;
        
        CGFloat width = [NSString widthForString:text fontSize:15 andHeight:15];
        
        UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(15+width, 3, 15, 19)];
        imageview.image = Image(@"tuhao_home_hot");
        [cell.contentView addSubview:imageview];
        
        return cell;
    }
    else{
        
        THHotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:hotCellID forIndexPath:indexPath];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.section) {
        return  9 * GRIDW;
    }else if(1 == indexPath.section){
        return 50;
    }else if(3 == indexPath.section){
        return 40;
    }else if(2 == indexPath.section){
        return 160;
    }else{
        return 120;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0 || indexPath.section == 3) return;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *headerView = [[UIView alloc]init];
    headerView.backgroundColor = kUIColorFromRGB(0xeeeeee);
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (4 < section) {
        return 2;
    }else if (4 == section){
        return 1;
    }else if (0 == section){
        return 0;
    }
    return 8;
}

- (UIView *)background
{
    if (!_background) {
        _background = [[UIView alloc] init];
        _background.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.5];
        _background.userInteractionEnabled = YES;
        [[UIApplication sharedApplication].keyWindow addSubview:_background];
        
        [_background mas_makeConstraints:^(MASConstraintMaker *make)
         {
             make.edges.equalTo([UIApplication sharedApplication].keyWindow).width.insets(UIEdgeInsetsMake(0, 0, 0, 0));
         }];
        _background.hidden = YES;
    }
    return _background;
}


@end
